 <style lang="scss">
[mode='xml'] {
  .plumb-layout__tools {
    display: none;
  }
}
.cus-layout-editor {
  .plumb-layout__item-action {
    display: flex;
    align-items: center;
    //> *:first-child {
    //  width: 150px;
    //}
  }
  .plumb-layout .header {
    > * {
      display: flex;
      > *:first-child {

        //height: 0;
        > *:first-child {

          display: none;
        }
      }
    }
  }
}
</style>

<template>
  <div class="cus-layout-editor">
    <template v-if="inited">
      <!--    {{widgetConfig.enums}}-->
      <el-row type="flex" >

        <el-button size="small" @click="openDialog">打开编辑</el-button>
<!--        <el-button size="small" @click="importFun">导入</el-button>-->
<!--        <el-button size="small" @click="exportFun">导出</el-button>-->
        <!--      <el-button @click="getXML">获取xml</el-button>-->
        <el-popover
            v-model:visible="state.previewVisible"
            placement="bottom"
            title=""
            :width="600"
            trigger="click"
        >
          <template #reference>
            <el-button size="small" @click="state.previewVisible = !state.previewVisible">XML预览</el-button>
          </template>
          <EwXmlShower :value="getXMLDisplay(state.value)"></EwXmlShower>
        </el-popover>
<!--        <el-button   size="small"-->
<!--                   @click="importFun">导入</el-button>-->
      </el-row>
      <el-dialog
          v-model="state.dialogVisible"
          title="DOM编辑" width="80vw"
          :close-on-click-modal="false"
          :append-to-body="true"
          @closed="onClosed"
      >
        <div :mode="widgetConfig.mode">
          <el-row class="a-space-mb-10">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="primary"
                       @click="exportFun">导出</el-button>
            <el-button  type="primary"
                         @click="importFun">导入</el-button>
          </el-row>
          <div>
            <!--          {{state.value}}-->
            <EwXmlShower :value="getXMLDisplay(state.value)"></EwXmlShower>
            <!--          <el-input type="textarea" readonly-->
            <!--                    :value="getXMLDisplay(state.value)"></el-input>-->
          </div>
          <ZLayoutEditor
              :ref="setLayoutRef"
              :controls="false"
              @ele-drag-change="onEleDragChange"
              :store-prefix="storePrefix"
              :auto-load="false"
              @plumb-inited="onPlumbInited"
              @mode:update:all="onPlumbUpdate"
              @del-dep="onPlumbDelDep"
              @save-layout="onSaveLayout"
              :weapp="widgetConfig.weapp"
              :handle-list1="handleList1"
          ></ZLayoutEditor>
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import {CustomRenderControlMixin, defineCustomRender} from "@/plugins/form-render/utils";
import ZLayoutEditor from "@/plugins/z-frame/components/ZLayoutEditor.vue";
import {onBeforeUnmount} from "vue";
import {clearPlumbLayoutStorage} from "@/plugins/PlumbLayout/mixin";
import EwXmlShower from "@/components/Ew/EwXmlShower.vue";
import {getXmlData, getMiniAppXmlData, getHtmlXmlData} from "@/views/about/components/PlumbLayout/xmlData";

async function cachedArrOperate(key = '', fun = () => {} ) {
  let cachedKeys = await ZY_EXT.store.getItem(key)
  if (!Array.isArray(cachedKeys)) {
    cachedKeys = []
  }
  // cachedKeys.push(v)
  cachedKeys = await fun(cachedKeys);
  await ZY_EXT.store.setItem(key, cachedKeys)
}

const OPERATE_PREFIX = 'layout-store-prefix'

export default {
  name: 'CusLayoutEditor',
  components: {EwXmlShower, ZLayoutEditor},
  mixins: [
    CustomRenderControlMixin
  ],
  setup(props, ctx) {
    let {part_key} = props.defs;
    let obj;
    let JSON5 = ZY.JSON5;
    let storePrefix = ZY.rid(6);

    (async function () {
      await cachedArrOperate(OPERATE_PREFIX, (arr) => {

        arr.forEach(cachedKey => {
          clearPlumbLayoutStorage(cachedKey)
        })

        return []
      })
    })();

    let locks = true
    let { data, methods, listeners, init, widgetConfig2 } = defineCustomRender(props, ctx, {
      handleValueInit(newVal) {
        if (!newVal) {
          newVal = '{data: {links: [], deps: []}, posMap: {}}'
        }
        if (newVal) {
          obj = JSON5.parse(newVal)
        }
        // openDialog()
        return newVal
      }
    })
    let state = data({
      dialogVisible: false,
      previewVisible: false
    })
    init(props)

    async function openDialog() {
      state.dialogVisible =true

      await cachedArrOperate(OPERATE_PREFIX, (arr) => {
        return arr.concat([storePrefix])
      })
    }

    let cachedPlumbContext = null
    async function importData(context, obj) {
      await context.importToolsData(obj)
      await ZY.sleep(300)
      await context.saveCache2Storage(obj)
    }

    async function onPlumbInited({context}) {
      console.log('handleValueInit', part_key, obj, context)
      importData(context, obj)
      cachedPlumbContext = context
    }


    let layoutRef = null
    function setLayoutRef(target, options) {
      layoutRef = target
    }

    function onSaveLayout(e) {
      console.log('onSaveLayout', e)
    }

    function getXML() {
      let v = layoutRef.getXML()
      // console.log('getXML', v)
    }

    function onEleDragChange() {
      // console.log('onEleDragChange')
    }

    async function save() {
      let v = layoutRef.getToolsData()
      // console.log('getToolsData', v)
      await layoutRef.saveCache2Storage(v)
      let ret = JSON5.stringify(v)

      methods.onChange(ret)
    }

    async function onClosed() {
      await save();
    }

    function getXMLDisplay(v) {
      return getApp().buildAllXml(v)
    }

    function onPlumbUpdate(e) {
      // let { model, key, newVal, config } = e
      let v = layoutRef.getToolsData()
      // console.log(ret)
      state.value = JSON5.stringify(v)
    }

    function onPlumbDelDep() {
      let v = layoutRef.getToolsData()
      // console.log(ret)
      state.value = JSON5.stringify(v)
    }

    function handleList1() {
      if (widgetConfig2.dragLib === 'base') {
        return getHtmlXmlData().concat(getMiniAppXmlData())
      }
      return getXmlData()
    }

    async  function importFun() {
      let str = await ZY2.fileOpenJSON5()
      if (str) {
        let obj = ZY.JSON5.parse(str)
        // console.log(obj, cachedPlumbContext)
        await importData(cachedPlumbContext, obj)
        await ZY.sleep(1000)
        state.value = str
      }
    }

    async function exportFun() {
      let v = layoutRef.getToolsData()
      let ret = JSON5.stringify(v)
      let inputTplName = await getApp().confirmMessageBox({
        label: '文件名',
        options: {
          showCancelButton: false
        }
      })

      await ZY_EXT.saveJSONFile({
        data: ret, fileName: inputTplName, prefix: 'slots__',
      })
    }

    onBeforeUnmount(() => {
      if (layoutRef) {
        layoutRef.clearLayoutStorage()
      }
    })

    return {
      state,
      getXML,
      openDialog,
      onPlumbInited,
      onEleDragChange,
      onClosed,
      onSaveLayout,
      importFun,
      exportFun,
      storePrefix,
      save,
      setLayoutRef,
      handleList1,
      onPlumbUpdate,
      getXMLDisplay,
      onPlumbDelDep,
      widgetConfig: widgetConfig2,
      methods,
      listeners,
    }
  },
}
</script>

